package cn.com.libertymutual.sp.service.impl;

import java.sql.DataTruncation;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.SysOperationLog;
import cn.com.libertymutual.sp.bean.TbSpAdconfig;
import cn.com.libertymutual.sp.dao.AdConfigDao;
import cn.com.libertymutual.sp.dao.OperationLogDao;
import cn.com.libertymutual.sp.service.api.AdConfigService;

@Service("adConfigService")
public class AdConfigServiceImpl implements AdConfigService {

	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private AdConfigDao adConfigDao;
	@Autowired
	private OperationLogDao operationLogDao;
	@Resource
	private RedisUtils redisUtils;

	// @Override
	// public ServiceResult advertList(String sorttype) {
	// ServiceResult sr = new ServiceResult();
	// Sort sort = null;
	// if ("ASC".equals(sorttype)) {
	// sort = new Sort(Direction.ASC, "serialNo");
	// } else {
	// sort = new Sort(Direction.DESC, "serialNo");
	// }
	//
	// sr.setResult(adConfigDao.findAll(new Specification<TbSpAdconfig>() {
	// @Override
	// public Predicate toPredicate(Root<TbSpAdconfig> root, CriteriaQuery<?>
	// query, CriteriaBuilder cb) {
	//
	// return cb.equal(root.get("isShow").as(String.class), "1");
	// }
	// }, sort));
	// return sr;
	// }

	@Override
	public ServiceResult advertList(String sorttype) {
		ServiceResult sr = new ServiceResult();
		List<TbSpAdconfig> dblist = null;
		dblist = (List<TbSpAdconfig>) redisUtils.get(Constants.AD_CONFIG_INFO + sorttype);
		if (null != dblist && dblist.size() != 0) {
			sr.setResult(dblist);
		} else {
			Sort sort = new Sort(Direction.ASC, "serialNo");
			dblist = adConfigDao.findAll(new Specification<TbSpAdconfig>() {
				@Override
				public Predicate toPredicate(Root<TbSpAdconfig> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

					return cb.equal(root.get("isShow").as(String.class), "1");
				}
			}, sort);
			log.info(dblist.toString());
			redisUtils.set(Constants.AD_CONFIG_INFO + sorttype, dblist);
		}
		List<TbSpAdconfig> reAdList = new ArrayList<TbSpAdconfig>();
		for (int i = 0; i < dblist.size(); i++) {
			TbSpAdconfig ad = dblist.get(i);
			Date date = new Date();
			long dateTime = date.getTime();
			if (null != ad.getStartDate() && null != ad.getEndDate() && dateTime > ad.getStartDate().getTime()
					&& dateTime < ad.getEndDate().getTime()) {
				reAdList.add(ad);
			}
		}
		sr.setResult(reAdList);
		return sr;
	}

	@Override
	public ServiceResult adConfigListWeb(String isShow, String toUrl, String adType, int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.ASC, "serialNo");

		sr.setResult(adConfigDao.findAll(new Specification<TbSpAdconfig>() {
			@Override
			public Predicate toPredicate(Root<TbSpAdconfig> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(isShow) && !"-1".equals(isShow)) {
					log.info(isShow);
					predicate.add(cb.equal(root.get("isShow").as(String.class), isShow));
				}
				if (StringUtils.isNotEmpty(toUrl)) {
					log.info(toUrl);
					predicate.add(cb.equal(root.get("toUrl").as(String.class), toUrl));
				}
				if (StringUtils.isNotEmpty(adType)) {
					log.info(adType);
					predicate.add(cb.equal(root.get("adType").as(String.class), adType));
				}
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort)));
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult addAdvert(TbSpAdconfig tbSpAdconfig) throws DataTruncation {

		ServiceResult sr = new ServiceResult();
		TbSpAdconfig ad = adConfigDao.save(tbSpAdconfig);
		sr.setResult(ad);
		SysOperationLog operLog = new SysOperationLog();
		operLog.setIP(Current.IP.get());
		operLog.setLevel("1");
		operLog.setModule("广告配置");
		operLog.setOperationTime(new Date());
		operLog.setUserId(Current.userInfo.get().getUserId());
		operLog.setContent("添加广告-ID:" + ad.getId());
		operationLogDao.save(operLog);
		redisUtils.deletelike(Constants.AD_CONFIG_INFO);
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult updateAdvert(TbSpAdconfig tbSpAdconfig) {
		ServiceResult sr = new ServiceResult();
		TbSpAdconfig ad = adConfigDao.save(tbSpAdconfig);
		sr.setResult(ad);
		SysOperationLog operLog = new SysOperationLog();
		operLog.setIP(Current.IP.get());
		operLog.setLevel("2");
		operLog.setModule("广告配置");
		operLog.setOperationTime(new Date());
		operLog.setUserId(Current.userInfo.get().getUserId());
		operLog.setContent("修改广告-ID:" + ad.getId());
		operationLogDao.save(operLog);
		redisUtils.deletelike(Constants.AD_CONFIG_INFO);
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult removeAdvert(String[] list) {
		ServiceResult sr = new ServiceResult();
		for (int i = 0; i < list.length; i++) {
			adConfigDao.deleteById(Integer.parseInt(list[i]));
			SysOperationLog operLog = new SysOperationLog();
			operLog.setIP(Current.IP.get());
			operLog.setLevel("3");
			operLog.setModule("广告配置");
			operLog.setOperationTime(new Date());
			operLog.setUserId(Current.userInfo.get().getUserId());
			operLog.setContent("删除广告-ID:" + Integer.parseInt(list[i]));
			operationLogDao.save(operLog);
			redisUtils.deletelike(Constants.AD_CONFIG_INFO);
		}
		sr.setSuccess();
		return sr;
	}

	@Override
	public ServiceResult getAdDetail(Integer id) {
		ServiceResult sr = new ServiceResult();
		sr.setResult(adConfigDao.findById(id));
		return sr;
	}

	@Override
	public ServiceResult updateAdDetail(Integer id, String detail) {
		ServiceResult sr = new ServiceResult();
		TbSpAdconfig ad = adConfigDao.findById(id).get();
		ad.setDetail(detail);
		sr.setResult(adConfigDao.save(ad));
		redisUtils.deletelike(Constants.AD_CONFIG_INFO);
		return sr;
	}
}
